<?php

namespace app\common\lib\sms;

use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use think\facade\Log;
use app\common\lib\sms\SmsInterface;

class Alisms implements SmsInterface
{
    public static function sendCode(string $phoneNumber, int $code)
    {
        if (empty($phoneNumber) || empty($code)) {
            return false;
        }
        AlibabaCloud::accessKeyClient(config('aliyun.access_key_id'), config('aliyun.access_key_secret'))
// use STS Token
// AlibabaCloud::stsClient('<your-access-key-id>', '<your-access-key-secret>', '<your-sts-token>')
                        ->regionId('cn-hangzhou')
                        ->asDefaultClient();
        try {
            $result = AlibabaCloud::rpc()
                          ->product('Dysmsapi')
                          // ->scheme('https') // https | http
                          ->version('2017-05-25')
                          ->action('SendSms')
                          ->method('POST')
                          ->host('dysmsapi.aliyuncs.com')
                          ->options([
                                        'query' => [
                                            'SignName' => config('aliyun.sign_name'),
                                            'TemplateCode' => config('aliyun.templateCode'),
                                            'PhoneNumbers' => $phoneNumber,
                                        ],
                                    ])
                          ->request();
            print_r($result->toArray());
        } catch (ClientException $e) {
            // Log::error("sms_ClientException_{$phoneNumber}", $e->getErrorMessage());
            return false;
            // echo $e->getErrorMessage() . PHP_EOL;
        } catch (ServerException $e) {
            // Log::error("sms_ServerException_{$phoneNumber}", $e->getErrorMessage());
            return false;
            // echo $e->getErrorMessage() . PHP_EOL;
        }
        return true;
    }
}
